package com.chengxiaoxiao.web.controller;

import com.chengxiaoxiao.commons.Page;
import com.chengxiaoxiao.constant.Constants;
import com.chengxiaoxiao.constant.DbConstants;
import com.chengxiaoxiao.domain.*;
import com.chengxiaoxiao.domain.Books;
import com.chengxiaoxiao.domain.json.*;
import com.chengxiaoxiao.service.*;
import com.chengxiaoxiao.service.impl.*;
import com.chengxiaoxiao.utils.JSONUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

//@WebServlet("/client/ClientServlet")
public class ClientServlet extends HttpServlet {

    AppinfoService appinfoService = new AppinfoServiceImpl();
    UsersService usersService = new UsersServiceImpl();
    ApppptService apppptService = new ApppptServiceImpl();
    CategoryService categoryService = new CategoryServiceImpl();
    BookService bookService = new BookServiceImpl();
    BorrowService borrowService = new BorrowServiceImpl();
    NoticeService noticeService = new NoticeServiceImpl();
    ReturnsService returnsService = new ReturnsServiceImpl();
    OrderService orderService = new OrderServiceImpl();


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String op = request.getParameter("op");
        if ("getnewVersion".equalsIgnoreCase(op)) {
            checkVersion(request, response);
        } else if ("login".equalsIgnoreCase(op)) {
            login(request, response);
        } else if ("ppt".equalsIgnoreCase(op)) {
            getPpt(request, response);
        } else if ("rankBook".equalsIgnoreCase(op)) {
            rankBook(request, response);
        } else if ("getCatrgory".equalsIgnoreCase(op)) {
            //获取类别信息
            getCatrgory(request, response);
        } else if ("getBooksbyCategory".equalsIgnoreCase(op)) {
            getBooksCategory(request, response);
        } else if ("getBooksByid".equalsIgnoreCase(op)) {
            getbooksById(request, response);
        } else if ("hotBook".equalsIgnoreCase(op)) {
            hotBook(request, response);
        } else if ("newbook".equalsIgnoreCase(op)) {
            newBook(request, response);
        } else if ("hotAuthor".equalsIgnoreCase(op)) {
            hotAuthor(request, response);
        } else if ("listnotice".equalsIgnoreCase(op)) {
            listNotice(request, response);
        } else if ("getuserInfo".equalsIgnoreCase(op)) {
            getUserInfo(request, response);
        } else if ("getBookByIsbn".equalsIgnoreCase(op)) {
            getBookByIsbn(request, response);
        } else if ("borrow".equalsIgnoreCase(op)) {
            borrow(request, response);
        } else if ("return".equalsIgnoreCase(op)) {
            returnBook(request, response);
        } else if ("getIsAllowBorrow".equalsIgnoreCase(op)) {
            getIsAllowBorrow(request, response);
        } else if ("getBorrow".equalsIgnoreCase(op)) {
            getBorrow(request, response);
        } else if ("getBorrowById".equalsIgnoreCase(op)) {
            getBorrowById(request, response);
        } else if ("recommend".equalsIgnoreCase(op)) {
            recommend(request, response);
        } else if ("addorder".equalsIgnoreCase(op)) {
            addOrder(request, response);
        }
        else if("search".equalsIgnoreCase(op))
        {
            search(request,response);
        }

    }

    /**
     * 搜索
     * @param request
     * @param response
     */
    private void search(HttpServletRequest request, HttpServletResponse response) {

        String bookName = request.getParameter("bookName");
        Page page =bookService.getListPageByBookName(1+"",bookName);

        List<Books> list =page.getRecords();

        List<CategoryBooks> listbook = new ArrayList<>();
        for (int i = 0; i < page.getRecords().size(); i++) {
            Books book = (Books) page.getRecords().get(i);

            CategoryBooks categoryBooks = new CategoryBooks();
            categoryBooks.setId(book.getId());
            categoryBooks.setAuthor(book.getAuthor());
            categoryBooks.setBookName(book.getBookName());
            categoryBooks.setCategoryName(book.getCategory().getName());
            categoryBooks.setNumber(book.getNumber());
            categoryBooks.setAddress(book.getAddress());
            categoryBooks.setImagesPath(book.getImagesSrc());
            listbook.add(categoryBooks);
        }

        JSONUtils.toJsonArray(response, listbook);

    }

    /**
     * 添加预订
     *
     * @param request
     * @param response
     */
    private void addOrder(HttpServletRequest request, HttpServletResponse response) {
        String userId = request.getParameter("userId");
        String bookId = request.getParameter("bookId");

        Order o = new Order();
        o.setBookId(Integer.parseInt(bookId));
        o.setUserId(Integer.parseInt(userId));
        o.setSubTime(new Date());

        orderService.add(o);

        HashMap<String, String> map = new HashMap<>();

        map.put(Constants.JSON_RESPONSE_KEY_STATUS, "ok");
        map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "预订成功");
        JSONUtils.toJson(response, map);
    }

    /**
     * 智能推荐
     *
     * @param request
     * @param response
     */
    private void recommend(HttpServletRequest request, HttpServletResponse response) {

        String uid = request.getParameter("uid");
        String num = request.getParameter("num");
        Users user = usersService.getUserInfoByUid(uid);

        if (user == null) {
            Page page = bookService.getListPage(num);
            List<Books> list = page.getRecords();
            List<BookImageAddress> listSimple = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                Books item = list.get(i);
                BookImageAddress b = new BookImageAddress((int) item.getId(), item.getBookName(), item.getImagesSrc(), item.getAddress());
                listSimple.add(b);
            }

            JSONUtils.toJsonArray(response, listSimple);
            return;
        }

        List<Borrow> list = borrowService.getBorrow(user.getId() + "");

        List<BookImageAddress> listSimple = new ArrayList<>();
        List<Integer> listCid = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Borrow b = list.get(i);
            int cid = (int) b.getBook().getCategory_Id();
            if (!listCid.contains(cid)) {
                listCid.add(cid);
            }
        }

        for (int i = 0; i < listCid.size(); i++) {
            List<Books> listBook = bookService.getBooksByCategory(listCid.get(i) + "");
            for (int j = 0; j < listBook.size(); j++) {
                Books item = listBook.get(j);
                BookImageAddress bia = new BookImageAddress((int) item.getId(), item.getBookName(), item.getImagesSrc(), item.getAddress());
                listSimple.add(bia);
            }
        }

        JSONUtils.toJsonArray(response, listSimple);

    }

    /**
     * 获取指定ID的借阅情况
     *
     * @param request
     * @param response
     */
    private void getBorrowById(HttpServletRequest request, HttpServletResponse response) {

        String borrId = request.getParameter("borrId");

        Borrow b = borrowService.getbyId(Integer.parseInt(borrId));

        BorrowApi api = new BorrowApi();
        api.setId((int) b.getId());
        String subTime = convertTime(b.getSubTime());
        api.setSubTime(subTime);
        api.setBookId(b.getBookId());
        api.setExpireTime(convertTime(b.getExpireTime()));
        api.setIsDeory(b.getIsDeory());
        api.setIsReturn(b.getIsReturn());
        api.setUserId(b.getUserId());
        api.setBookName(b.getBook().getBookName());
        api.setImageSrc(b.getBook().getImagesSrc());
        api.setAuthor(b.getBook().getAuthor());
        api.setIsbn(b.getBook().getIsbn());

        JSONUtils.toJson(response, api);
    }

    /**
     * 获取指定用户的借书情况
     *
     * @param request
     * @param response
     */
    private void getBorrow(HttpServletRequest request, HttpServletResponse response) {

        String userId = request.getParameter("userId");

        Users user = usersService.getUserInfoByUid(userId);

        HashMap<String, String> map = new HashMap<>();
        if (user == null) {
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "用户不存在");
            JSONUtils.toJson(response, map);
            return;
        }

        List<Borrow> list = borrowService.getBorrow(user.getId() + "");


        List<BorrowApi> borrowApiList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Borrow b = list.get(i);
            BorrowApi api = new BorrowApi();
            api.setId((int) b.getId());
            String subTime = convertTime(b.getSubTime());
            api.setSubTime(subTime);
            api.setBookId(b.getBookId());
            api.setExpireTime(convertTime(b.getExpireTime()));
            api.setIsDeory(b.getIsDeory());
            api.setIsReturn(b.getIsReturn());
            api.setUserId(b.getUserId());
            api.setBookName(b.getBook().getBookName());
            api.setImageSrc(b.getBook().getImagesSrc());
            borrowApiList.add(api);
        }

        JSONUtils.toJsonArray(response, borrowApiList);
    }

    private String convertTime(Date subTime) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(subTime);
    }

    /**
     * 获取用户是否可以借书
     *
     * @param request
     * @param response
     */
    private void getIsAllowBorrow(HttpServletRequest request, HttpServletResponse response) {

        String userId = request.getParameter("userId");

        Users user = usersService.getUserInfoByUid(userId);

        HashMap<String, String> map = new HashMap<>();
        if (user.getIsBlack() == 1) {
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "您的账户存在安全问题，已被系统自动冻结账户");
            JSONUtils.toJson(response, map);
            return;
        }


        int borrowNum = user.getMostBorrowNum();

        int alreadyCount = borrowService.getBorrowCountByUser(user.getId());


        if (borrowNum <= alreadyCount) {
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "您当前最多借阅" + borrowNum + "本书，当前已借阅" + alreadyCount + "本，已超过最大限制");
            JSONUtils.toJson(response, map);
            return;
        }

        map.put(Constants.JSON_RESPONSE_KEY_STATUS, "ok");
        JSONUtils.toJson(response, map);
    }

    /**
     * 还书
     *
     * @param request
     * @param response
     */
    private void returnBook(HttpServletRequest request, HttpServletResponse response) {
        String userid = request.getParameter("userId");
        String bookId = request.getParameter("bookId");
        String adminId = request.getParameter("adminId");

        Users user = usersService.getUserInfoByUid(userid);

        Borrow borrow = borrowService.getBorrowNoReturn(user.getId() + "", bookId);

        HashMap<String, String> map = new HashMap<>();

        if (borrow == null) {
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "书籍信息验证错误，请确认书籍信息！");
            JSONUtils.toJson(response, map);
            return;
        }
        borrow.setIsReturn(DbConstants.BORRROW_ISRETURN_TRUE);

        borrowService.update(borrow);


        Books books = bookService.getbyId(Integer.parseInt(bookId));

        books.setNumber(books.getNumber() + 1);

        bookService.update(books);


        Returns returns = new Returns();

        returns.setBookId(borrow.getBookId());
        returns.setSubTime(new Date());
        returns.setUserId(borrow.getUserId());
        returns.setBorrowId((int) borrow.getId());


        returnsService.add(returns);

        map.put(Constants.JSON_RESPONSE_KEY_STATUS, "ok");
        map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "还书成功");
        JSONUtils.toJson(response, map);

    }

    /**
     * 借书
     *
     * @param request
     * @param response
     */
    private void borrow(HttpServletRequest request, HttpServletResponse response) {
        String userid = request.getParameter("userId");
        String bookId = request.getParameter("bookId");
        String adminId = request.getParameter("adminId");

        Users user = usersService.getUserInfoByUid(userid);

        int borrowNum = user.getMostBorrowNum();

        int alreadyCount = borrowService.getBorrowCountByUser(user.getId());

        HashMap<String, String> map = new HashMap<>();
        if (borrowNum <= alreadyCount) {
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "您当前最多借阅" + borrowNum + "本书，当前已借阅" + alreadyCount + "本，已超过最大限制");
            JSONUtils.toJson(response, map);
            return;
        }

        //TODO:删除预订信息

        Books books = bookService.getbyId(Integer.parseInt(bookId));

        books.setNumber(books.getNumber() - 1);

        bookService.update(books);

        Borrow borrow = new Borrow();
        borrow.setBookId(Integer.parseInt(bookId));
        borrow.setUserId(user.getId());
        borrow.setSubTime(new Date());
        borrowService.add(borrow);

        map.put(Constants.JSON_RESPONSE_KEY_STATUS, "ok");
        map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "借阅成功");
        JSONUtils.toJson(response, map);

    }

    /**
     * 根据isbn查询书籍信息
     *
     * @param request
     * @param response
     */
    private void getBookByIsbn(HttpServletRequest request, HttpServletResponse response) {
        String isbn = request.getParameter("isbn");
        try {

            Books book = bookService.getBookbyIsbn(isbn);

            com.chengxiaoxiao.domain.json.Books b = new com.chengxiaoxiao.domain.json.Books();
            b.setId(book.getId());
            b.setAddress(book.getAddress());
            b.setAuthor(book.getAuthor());
            b.setCategoryName(book.getCategory().getName());
            b.setDescript(book.getDescript());
            b.setImagesSrc(book.getImagesSrc());
            b.setIsbn(book.getIsbn());
            b.setName(book.getBookName());
            b.setNumber(book.getNumber());
            b.setPrice(book.getPrice());
            b.setPublisherName(book.getPublisher().getName());

            JSONUtils.toJson(response, b);

        } catch (Exception e) {

            throw new RuntimeException(e);
        }


    }

    /**
     * 根据用户名，获取用户信息
     *
     * @param request
     * @param response
     */
    private void getUserInfo(HttpServletRequest request, HttpServletResponse response) {
        String uid = request.getParameter("uid");
        Users user = usersService.getUserInfoByUid(uid);

        HashMap<String, String> map = new HashMap<String, String>();
        if (user == null) {
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "用户不存在");
            JSONUtils.toJson(response, map);
            return;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setRealName(user.getRealName());
        userInfo.setAddress(user.getUsersExtra().getAddress());
        userInfo.setBorrowNum(user.getMostBorrowNum());
        userInfo.setClasses(user.getClasses().getClasses().getName() + "-" + user.getClasses().getName());
        userInfo.setEmail(user.getUsersExtra().getEmail());
        userInfo.setGender(user.getGender());
        userInfo.setIsTeacher(user.getUsersExtra().getIsTeacher());
        userInfo.setStuNum(user.getStudentNum());

        JSONUtils.toJson(response, userInfo);
    }

    /**
     * 显示公告
     *
     * @param request
     * @param response
     */
    private void listNotice(HttpServletRequest request, HttpServletResponse response) {

        String num = request.getParameter("num");

        Page page = noticeService.getListPage(num);
        JSONUtils.toJsonArray(response, page.getRecords());
    }

    /**
     * 获取热门作者
     *
     * @param request
     * @param response
     */
    private void hotAuthor(HttpServletRequest request, HttpServletResponse response) {

        String num = request.getParameter("num");
        Page page = borrowService.getListPageHotAuthor(num);
        List<Author> list = page.getRecords();

        List<AuthorAndImage> listAuthorImage = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            Author item = list.get(i);
            AuthorAndImage authorAndImage = borrowService.getAuthorAndImage(item.getAuthor());
            listAuthorImage.add(authorAndImage);
        }

        JSONUtils.toJsonArray(response, listAuthorImage);
    }

    /**
     * 新书榜
     *
     * @param request
     * @param response
     */
    private void newBook(HttpServletRequest request, HttpServletResponse response) {
        String num = request.getParameter("num");
        Page page = borrowService.getListPageNewRank(num);

        List<Books> list = page.getRecords();
        List<CategoryBooks> listbook = new ArrayList<>();
        for (int i = 0; i < page.getRecords().size(); i++) {
            Books book = (Books) page.getRecords().get(i);

            CategoryBooks categoryBooks = new CategoryBooks();
            categoryBooks.setId(book.getId());
            categoryBooks.setAuthor(book.getAuthor());
            categoryBooks.setBookName(book.getBookName());
            categoryBooks.setCategoryName(book.getCategory().getName());
            categoryBooks.setNumber(book.getNumber());
            categoryBooks.setAddress(book.getAddress());
            categoryBooks.setImagesPath(book.getImagesSrc());
            listbook.add(categoryBooks);
        }

        JSONUtils.toJsonArray(response, listbook);

    }

    /**
     * 热门书籍
     *
     * @param request
     * @param response
     */
    private void hotBook(HttpServletRequest request, HttpServletResponse response) {
        String num = request.getParameter("num");
        Page page = borrowService.getListPageBorrowRank(num);

        List<Books> list = page.getRecords();
        List<CategoryBooks> listbook = new ArrayList<>();
        for (int i = 0; i < page.getRecords().size(); i++) {
            Books book = (Books) page.getRecords().get(i);

            CategoryBooks categoryBooks = new CategoryBooks();
            categoryBooks.setId(book.getId());
            categoryBooks.setAuthor(book.getAuthor());
            categoryBooks.setBookName(book.getBookName());
            categoryBooks.setCategoryName(book.getCategory().getName());
            categoryBooks.setNumber(book.getNumber());
            categoryBooks.setAddress(book.getAddress());
            categoryBooks.setImagesPath(book.getImagesSrc());
            listbook.add(categoryBooks);
        }

        JSONUtils.toJsonArray(response, listbook);


    }

    /**
     * 通过ID获取书籍详细信息
     *
     * @param request
     * @param response
     */
    private void getbooksById(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        try {
            int ids = Integer.parseInt(id);
            Books book = bookService.getbyId(ids);

            com.chengxiaoxiao.domain.json.Books b = new com.chengxiaoxiao.domain.json.Books();
            b.setId(book.getId());
            b.setAddress(book.getAddress());
            b.setAuthor(book.getAuthor());
            b.setCategoryName(book.getCategory().getName());
            b.setDescript(book.getDescript());
            b.setImagesSrc(book.getImagesSrc());
            b.setIsbn(book.getIsbn());
            b.setName(book.getBookName());
            b.setNumber(book.getNumber());
            b.setPrice(book.getPrice());
            b.setPublisherName(book.getPublisher().getName());

            JSONUtils.toJson(response, b);

        } catch (Exception e) {

            throw new RuntimeException(e);
        }
    }

    /**
     * 获取分类下的书籍
     *
     * @param request
     * @param response
     */
    private void getBooksCategory(HttpServletRequest request, HttpServletResponse response) {

        String id = request.getParameter("id");
        String num = request.getParameter("num");


        Page page = bookService.getBooksByCategoryPage(id, num);

        List<CategoryBooks> listbook = new ArrayList<>();
        for (int i = 0; i < page.getRecords().size(); i++) {
            Books book = (Books) page.getRecords().get(i);

            CategoryBooks categoryBooks = new CategoryBooks();
            categoryBooks.setId(book.getId());
            categoryBooks.setAuthor(book.getAuthor());
            categoryBooks.setBookName(book.getBookName());
            categoryBooks.setCategoryName(book.getCategory().getName());
            categoryBooks.setNumber(book.getNumber());
            categoryBooks.setAddress(book.getAddress());
            categoryBooks.setImagesPath(book.getImagesSrc());
            categoryBooks.setPublisherName(book.getPublisher().getName());
            listbook.add(categoryBooks);
        }


        JSONUtils.toJsonArray(response, listbook);

    }

    /**
     * 获取类别信息
     *
     * @param request
     * @param response
     */
    private void getCatrgory(HttpServletRequest request, HttpServletResponse response) {
        List<Category> list = categoryService.getCatrgoryBooks();

        JSONUtils.toJsonArray(response, list);

    }

    /**
     * 图书榜单
     *
     * @param request
     * @param response
     */
    private void rankBook(HttpServletRequest request, HttpServletResponse response) {

        //String category = request.getParameter();

    }

    /**
     * 获取PPT图片
     *
     * @param request
     * @param response
     */
    private void getPpt(HttpServletRequest request, HttpServletResponse response) {
        List<Appppt> list = apppptService.get();

        JSONUtils.toJsonArray(response, list);
    }

    /**
     * 登录
     *
     * @param request
     * @param response
     */
    private void login(HttpServletRequest request, HttpServletResponse response) {
        String uid = request.getParameter("uid");
        String pwd = request.getParameter("pwd");

        Users user = usersService.login(uid, pwd);
        HashMap<String, String> map = new HashMap<String, String>();
        if (user == null) {
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "用户名或者密码错误");
            JSONUtils.toJson(response, map);
            return;
        }

        if (user.getIsBlack() == 1) {
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "您已被限制登录，请联系图书管理员");
            JSONUtils.toJson(response, map);
            return;
        }
        map.put(Constants.JSON_RESPONSE_KEY_STATUS, "ok");
        map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, user.getId() + "");
        JSONUtils.toJson(response, map);

    }

    /**
     * 检查更新
     *
     * @param request
     * @param response
     */
    private void checkVersion(HttpServletRequest request, HttpServletResponse response) {
        Appinfo info = appinfoService.getLastVersion();
        HashMap<String, String> map = new HashMap<>();

        map.put("versionName", info.getVersionNum());
        map.put("versionCode", info.getVersionCode() + "");
        map.put("des", info.getUpdateContent());
        map.put("url", info.getAddress());

        JSONUtils.toJson(response, map);


    }
}
